/**
 * 队列 queue
 * FIFO 先进先出， 添加元素在队列尾部，移除顶部元素
 */

function Queue() {
  let items = []

  this.push = function(value) {
    items.push(value)
  }

  this.shift = function() {
    return items.shift()
  }

  this.size = function() {
    return items.length
  }

  this.isEmpty = function() {
    return items.length == 0
  }

  this.front = function() {
    return items[0]
  }
  
  this.print = function() {
    console.log(items.toString())
  }
}

/**
 * 带有优先级的队列
 */
function PriorityQueue() {
  let items = []

  function QueueElement (element, priority) {
    this.element = element
    this.priority = priority
  }

  this.push = function(value, priority) {
    let queueElement = new QueueElement(value, priority)
    if(this.isEmpty()) {
      items.push(queueElement)
    } else {
      let canAdd = false
      for (let i = 0; i < items.length; i++) {
        const element = items[i];
        if(queueElement.priority < element.priority) { // priority越小 优先级越大
          items.splice(i, 0, queueElement)
          canAdd = true
          break
        }
      }
      if (!canAdd) items.push(queueElement)
    }
  }

  this.shift = function() {
    return items.shift()
  }

  this.size = function() {
    return items.length
  }

  this.isEmpty = function() {
    return items.length == 0
  }

  this.front = function() {0
    return items[0]
  }
  
  this.print = function() {
    console.log(items.toString())
  }
  
}

/**
 * 击鼓传花
 * @param {Array} playerList 玩家集合
 * @param {Number} times 传递次数
 */
function handleGame(playerList, times) {
  let queue = new Queue()
  // 添加玩家
  for (let i = 0; i < playerList.length; i++) {
    const element = playerList[i];
    queue.push(element)
  }
  let handle = 1
  while(queue.size() != 1) {
    if(handle == times) {
      let name = queue.shift()
      console.log(name + " 被淘汰")
      handle = 1
    } else {
      queue.push(queue.shift())
      handle ++ 
    }
  }
  console.log("Winner is " + queue.front())
}

let nameList = ['Jack', 'Tom', 'Maria', 'Michel', 'Green', 'James', 'Stephen', 'Howalld']
handleGame(nameList, 5)